package org.wby.jwt.config;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import org.springframework.web.cors.CorsConfigurationSource;
import org.wby.jwt.config.security.CustomAccessDeniedHandler;
import org.wby.jwt.config.security.JwtAuthcationFilter;

@EnableWebSecurity
@Configuration
public class MyWebSecurityConfig {
    @Resource
    CustomAccessDeniedHandler customAccessDeniedHandler;
    @Qualifier("webCorsConfigSource")
    @Autowired
    private CorsConfigurationSource corsConfigurationSource;
    @Resource
    JwtAuthcationFilter jwtAuthcationFilter;
    //请求拦截
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                //禁止网页iframe
                .headers(t->t.frameOptions(option->option.disable()))
                //关闭跨站点请求伪造csrf防护。使用jwt，所以禁用csrf.
                .csrf(t->t.disable())
//                .logout(t -> t.permitAll().clearAuthentication(false))
                .authorizeHttpRequests((authorize) -> authorize
                        .requestMatchers("/user/test","/register","/login").permitAll()

                )
                .authorizeHttpRequests(t -> t.anyRequest().authenticated())
                //配置允许跨域
                .cors(t -> t.configurationSource(corsConfigurationSource))

                ////前后端分离采用JWT 不需要session
                .sessionManagement(t -> t.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                //自定义权限拒绝处理类
                .exceptionHandling(t->t.accessDeniedHandler(customAccessDeniedHandler))
                //更改密码存储方式
//                .passwordManagement(password->password.changePasswordPage("/admin/changePassword"))
                //添加JWT认证过滤器
                .addFilterBefore(jwtAuthcationFilter, AuthorizationFilter.class)
//                .formLogin((login) -> login.permitAll())

        ;
        return http.build();
    }


}
